#include "ESMemcache.h"
using namespace std;

ESMemcache::ESMemcache(void)
{
}

ESMemcache::~ESMemcache(void)
{
}

int ESMemcache::setTimeOut(int msec)
{
	memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_CONNECT_TIMEOUT, msec);
	memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SND_TIMEOUT, msec);
	memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RCV_TIMEOUT, msec);
	memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RETRY_TIMEOUT, -1);
	return 0;
}

bool ESMemcache::Init(char* pIPPort, int msec)
{
	memc = memcached_create(NULL);
	int nPort = 0;
	char * pszPort = strchr(pIPPort, ':');
	if (pszPort) {
		nPort = atoi(pszPort + 1);
		*pszPort = 0;
	}
	setTimeOut(msec);
	rc = memcached_server_add(memc, pIPPort, nPort);
	if(rc != MEMCACHED_SUCCESS)
		return false;
	
	return rc == MEMCACHED_SUCCESS;
}


bool ESMemcache::SetRecord(char* key, const char* value, const size_t bytes, const time_t expire)
{
	rc = memcached_set(memc, key, strlen(key), value, bytes, expire, 0);
	return rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED;
}

bool ESMemcache::Replace(char* key, const char* value, const size_t bytes, const time_t expire)
{
	rc = memcached_replace(memc, key, strlen(key), value, bytes, expire, 0);
	return rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED;
}


void ESMemcache::GetRecord(const char* key, std::string &value)
{
	size_t value_length = 0;
	uint32_t flags = 0;
	char *val = memcached_get(memc, key, strlen(key), &value_length, &flags, &rc);
	if(val !=NULL)
	{
		value = val;
		free(val);
	}
	else
	{
		value.clear();
	}
}

bool ESMemcache::DeleteRecord(const char* key)
{

	rc = memcached_delete(memc, key, strlen(key), 0);
	return rc == MEMCACHED_SUCCESS;
}

bool ESMemcache::Increment(const char *key, int offset, uint64_t &value)
{
	rc = memcached_increment(memc, key, strlen(key), offset, &value);
	return rc == MEMCACHED_SUCCESS;
}

bool ESMemcache::Decrement(const char *key, int offset, uint64_t &value)
{
	rc = memcached_decrement(memc, key, strlen(key), offset, &value);
	return rc == MEMCACHED_SUCCESS;
}

bool ESMemcache::IsKeyExist(const char *key)
{
	size_t value_length = 0;
	uint32_t flags = 0;
	memcached_get(memc, key, strlen(key), &value_length, &flags, &rc);
	if (rc == MEMCACHED_NOTFOUND) {
		return false;
	}
	return true;
}

